<template>
  <transition enter-active-class="contextmenu-enter" leave-active-class="contextmenu-leave">
    <div class="contextmenu" ref="contextmenu" @click="onContextMenuClick" :style="contextmenuStyles"
         @contextmenu="onMenuContextmenu"
         v-show="isVisible">
      <ul class="cm-items">
        <li class="cm-item" v-for="item in items" :key="item.name"
            :class="`cm-item--${item.type || 'node'}`">
          <div class="cm-content">
            <span class="cm-icon" :class="item.icon"></span>
            <span class="cm-text">{{ item.label }}</span>
          </div>
        </li>
      </ul>
    </div>
  </transition>
</template>

<script>
import menuItems from './menu_items'

export default {
  name: 'Contextmenu',
  data() {
    return {
      items: null,
      cell: null,
      isVisible: false,
      offset: {
        x: 0,
        y: 0
      }
    }
  },
  mounted() {
    // window.addEventListener('click', this.onWindowClick)
    // window.addEventListener('contextmenu', this.onWindowClick)
  },
  beforeDestroy() {
    window.removeEventListener('contextmenu', this.onWindowClick)
    window.removeEventListener('click', this.onWindowClick)
  },
  methods: {
    show(type, e, x, y, cell) {
      // const toolbarRect = this.$refs.toolbar.getClientRects()[0]
      this.items = menuItems[type] || []
      this.cell = cell
      this.offset.x = x // + toolbarRect.width
      this.offset.y = y
      this.isVisible = true
    },
    onMenuContextmenu(e) {
      e.preventDefault()
      return false
    },
    onWindowClick() {
      if (this.isVisible) {
        this.isVisible = false
      }
    },
    onContextMenuClick(e) {
      console.log(e)
      // e.stopPropagation()
    }
  },
  computed: {
    contextmenuStyles() {
      return {
        transform: `translateX(${this.offset.x}px) translateY(${this.offset.y}px)`
      }
    }
  }
}
</script>

<style scoped>
.contextmenu {
  position: absolute;
  left: 0;
  width: auto;
  color: #555;
  background-color: #ffffff;
  box-shadow: 0 1px 8px 1px #aaaaaa;
  z-index: 3;
  user-select: none;
  font-size: 13px;
}

.cm-items {
  margin: 0;
  padding: 0;
  list-style: none;
}

.cm-item {
  margin: 0;
  padding: 0;
  cursor: pointer;
}

.cm-item--separator {
  border-bottom: 1px inset #efeff0;
}

.cm-item.cm-item--node:hover {
  background-color: #f9ffff;
  color: #0699ee;
}

.cm-item--node .cm-content {
  display: grid;
  line-height: 20px;
  min-width: 140px;
  grid-template-columns: 32px auto;
}

.cm-item--node .cm-icon {
  padding: 5px;
  height: 100%;
  /*border-right: 1px solid #efeff0;*/
  box-sizing: border-box;
}

.cm-item--node .cm-text {
  padding: 5px;
  text-align: left;
}
</style>
